<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>消息</title>
    <META  HTTP-EQUIV="Pragma" CONTENT="no-cache">
    <meta name="viewport" content="initial-scale=1.0,maximum-scale=1.0,minimum-scale=1.0,user-scalable=no,width=device-width" />
    <meta name="format-detection" content="telephone=no" />
    <meta name="app-mobile-web-app-capable" content="yes" />
    <meta name="app-mobile-web-app-status-bar-style" content="black-translucent" />
    <link rel="stylesheet" href="//at.alicdn.com/t/font_772560_th7q34itwge.css">
    <link rel="stylesheet" href="css/message.css">

</head>
<body>
<div id="content">



</div>
<script src="js/footer.js"></script>
<script src="https://cdn.bootcss.com/jquery/3.3.1/jquery.min.js"></script>
<script src="js/common.js"></script>



<!--web im sdk 最近联系人 api 示例代码-->

<script src="js/recentcontact/recent_contact_list_manager.js" type="text/javascript"></script>


<!--web im sdk-->

<script src="sdk/webim.js" type="text/javascript"></script>
<script src="js/global/global.js" type="text/javascript"></script>
<script type="text/javascript">
let ids =[]
let all_list = []

    window.onpageshow = function(event) {
        if (event.persisted) {
            window.location.reload();
        }
    };

    
    $(document).ready(function(){
        $("#content").on('click','.msg_wrap',function(){
            var name = $(this).find('.wx_name').html();
            var avatar = $(this).find('img').attr('src');
            var id = $(this).attr('id')
            gotochat(id,name,avatar)
        })
    });



    //newMsgList 为新消息数组，结构为[Msg]
    function onMsgNotify_list(newMsgList) {
        var sess, newMsg;
        for (var j in newMsgList) {//遍历新消息
            newMsg = newMsgList[j];
            var ID=newMsg.fromAccount;//用户标识
            var name = newMsg.fromAccountNick;//用户名
            var msgcontent = newMsg.elems[0].content.text;//内容
            var time = newMsg.time
            tmp = recentSessMap[ID];
            var result = $.inArray(ID, all_list)
            //console.error(all_list)
            if(result != -1)
            {
                var unreadcount = $("#noread"+ID).text();
                    unreadcount = parseInt(unreadcount) + 1;
                    $("#content"+ID).text(msgcontent);
                    $("#noread"+ID).text(unreadcount);
                    $("#noread"+ID).show();
                    $("#time"+ID).text(webim.Tool.formatTimeStamp(time));
                    $("#content").prepend($("#"+ID))
            }else{
                all_list.push(ID)
                getimgandnick(ID,function(x){
                    if(x != 'none')
                    {
                        create(ID,msgcontent,1,webim.Tool.formatTimeStamp(time),x.UserProfileItem[0].ProfileItem[0].Value,x.UserProfileItem[0].ProfileItem[1].Value);
                    }else{
                        create(ID,msgcontent,1,webim.Tool.formatTimeStamp(time),recentSessMap[j].SessionNick,recentSessMap[j].SessionImage);
                    }})}
        }
    }

    function gotochat(id,name,face)
    {
        sessionStorage.setItem('chatwith',id);
        window.location.href=encodeURI("./chat.html?name="+name+"&face="+face);
    }
    function create(id,content,noread,time,wx_name,wx_face)
    {

        var html = '<div id=' +id+ ' class="msg_wrap bg-white"> <div id=d2'+id+' class="msg_item flex"> <div id=d3'+id+' class="user_avatar">  <img id=img1'+id+ ' src="'+wx_face+'" alt=""> </div> <div id=d4'+id+' class="flex1 rt_msg"> ';
        var html = html + '<div id=d5'+id+' class="flex1 md_item flex align"> <p id=name'+id+ ' class="wx_name flex1">'+wx_name+'</p> <p id=time'+id+ ' class="gray">'+time+'</p> </div> <div id=d6'+id+' class="rt_item flex align"> <p id=content'+id+' class="gray flex1">'+content+'</p>';
        var html = html + '<div id=noread'+id+ ' class="msg_tips tc">'+noread+'</div> </div> </div> </div> </div>';
        $("#content").prepend(html);
        if(noread == 0)
        $("#noread"+id).hide();

    }

function getimgandnick(id,cb)
{
    if(ids == false)
    {
        return 0;
    }
     var data = {
            'From_Account' : sessionStorage.getItem('login_identifier'),
            'To_Account' : id,
            'TagList':['Tag_Profile_IM_Nick','Tag_Profile_IM_Image'],
            }

    $.ajax({url:'https://webim.tim.qq.com/v4/profile/portrait_get?websdkappid=537048168&v=1.7.0&platform=10&tinyid='+sessionStorage.getItem('login_tinyid')+'&a2='+sessionStorage.getItem('login_a2')+'&contenttype=json&sdkappid=1400114382&accounttype=31940&apn=1',type:"POST",data:JSON.stringify(data),success:function(result){
        var ret = JSON.parse(result)
        var item = ret.UserProfileItem
        for(var i in item)
        {
            try{
                var id = item[i].To_Account
                if(item[i].ProfileItem)
                {
                    
                    var name = item[i].ProfileItem[0].Value
                    var face = item[i].ProfileItem[1].Value
                    
                    localStorage.setItem(id+'__name__',name)
                    localStorage.setItem(id+'__face__',face)   
                }else{
                    var face = 'https://img.zcool.cn/community/01786557e4a6fa0000018c1bf080ca.png@2o.png'
                    var name = '-'

                }
                $("#img1"+id).attr("src",face);
                $("#name"+id).html(name);
                      

            }catch(e){
                console.error('errorerrorerror')
            }
            
        }
        
    }});
  
}

    //初始化联系人
    //recentSessMap{}最近联系人id，最近一条消息，时间，未读数
    function initUnreadMsgCount(){
        var sess;
        var sessMap=webim.MsgStore.sessMap();
        //console.error(sessMap);return

        //更新未读数
        for (var i in sessMap) {
            sess = sessMap[i];
            var time = webim.Tool.formatTimeStamp(sess.time())

            for(var j in recentSessMap)
            {
                if(recentSessMap[j].SessionId == sess.id())
                {
                    recentSessMap[j].unread = sess.unread();
                }
            }

        }

        recentSessMap.reverse()

        for (var j in recentSessMap){
            all_list.push(recentSessMap[j].SessionId)  
            create(recentSessMap[j].SessionId,recentSessMap[j].MsgShow,recentSessMap[j].unread,recentSessMap[j].MsgTimeStamp,' ',0);  
            //console.error(recentSessMap[j].SessionId+'__name__')
            if(localStorage.getItem(recentSessMap[j].SessionId+'__name__')!=null && localStorage.getItem(recentSessMap[j].SessionId+'__face__')!=null)
            {
                $("#img1"+recentSessMap[j].SessionId).attr("src",localStorage.getItem(recentSessMap[j].SessionId+'__face__'));
                $("#name"+recentSessMap[j].SessionId).html(localStorage.getItem(recentSessMap[j].SessionId+'__name__'));
                            
            }else{
                ids.push(recentSessMap[j].SessionId)  
                

            }
                  
        }
        
        getimgandnick(ids,function(x){console.error(x)})
    }



    function changelistener()
    {
        var listeners = {
            "onMsgNotify": onMsgNotify_list //监听新消息(私聊，普通群(非直播聊天室)消息，全员推送消息)事件，必填
            ,
            "onLongPullingNotify": function (data) {
                //console.debug('onLongPullingNotify', data)
            }
        };
        webim.changelistener(listeners , function(x){},function(x){console.error(x)});
    }

    window.onload =function()
    {      
        //进入该页面首先拉取最近联系人,并创建html样式
        //然后更换监听    
        changelistener();
        initRecentContactList();
    }

</script>









</body>
</html>